package lesson3.models;

import java2d.game.GameObject;
import java2d.game.Maths;
import java2d.game.Time;

import java.awt.*;
import java.awt.geom.Point2D;
import java.util.Random;

/**
 * Author:     Zhao Yan
 * DateTime:   2023/4/18 18:55
 */
public class EnemySpawner extends GameObject {

    public final Point2D direction = new Point2D.Double(0, 1);

    public double padding = 20;

    public boolean isHorizontal = true;

    public double minInterval = 1.0;

    public double maxInterval = 3.0;

    public double minEnemySpeed = 0.1;

    public double maxEnemySpeed = 0.3;

    private double interval;

    private double timer;

    private double halfWidth, halfHeight;

    private final Random random = new Random(System.nanoTime());

    private double x;

    private double y;

    public EnemySpawner(double x, double y) {
        this.x = x;
        this.y = y;
        nextInterval();
    }

    @Override
    protected void onActivated() {
        Dimension renderSize = getScene().getGame().getRenderSize();
        halfWidth = renderSize.width * 0.5;
        halfHeight = renderSize.height * 0.5;
        transform.setPosition(x, y);
    }

    private void nextInterval() {
        interval = random.nextDouble(minInterval, maxInterval);
    }

    @Override
    protected void onUpdate() {
        if (timer >= interval) {
            spawn();
            nextInterval();
            timer = 0;
        } else {
            timer += Time.deltaTime;
        }
    }

    private void spawn() {
        Enemy enemy = new Enemy();
        double x = random.nextDouble(-halfWidth + padding, halfWidth - padding);
        double y = random.nextDouble(-halfHeight + padding, halfHeight - padding);

        enemy.translator.speed = random.nextDouble(minEnemySpeed, maxEnemySpeed);
        Maths.normalize(direction);
        enemy.translator.direction.setLocation(direction);

        if (isHorizontal)
            enemy.transform.setPosition(x, transform.getPosition().getY());
        else
            enemy.transform.setPosition(transform.getPosition().getX(), y);

        getScene().add(enemy);
    }


}
